package cmd

import (
	"github.com/CIPFZ/collector/internal/app"
	"github.com/CIPFZ/collector/internal/core"
	"github.com/CIPFZ/collector/internal/types"
	"github.com/CIPFZ/collector/pkg/exception"

	"github.com/spf13/cobra"
	"go.uber.org/zap"
)

// NewCancelCommand 创建 cancel 命令
func NewCancelCommand(collector *app.Collector) *cobra.Command {
	opts := &types.CancelOptions{}

	cmd := &cobra.Command{
		Use:   "cancel",
		Short: "Cancel running collection tasks",
		Long: `Cancel currently running collection tasks gracefully or forcefully.

Examples:
  collector cancel --task-id 123456              # Cancel specific task
  collector cancel --task-id 123456 --force      # Force cancel task`,
		RunE: func(cmd *cobra.Command, args []string) error {
			if opts.TaskID == "" {
				return exception.NewNotTaskIdError("missing required flag: --task-id")
			}
			logger := collector.Logger()
			logger.Info("Cancelling collection tasks",
				zap.String("task_id", opts.TaskID),
				zap.Bool("force", opts.Force),
			)
			// 任务取消
			err := core.CancelTaskWithPID(collector, opts)
			if err != nil {
				return err
			}
			return nil
		},
	}

	cmd.Flags().StringVar(&opts.TaskID, "task-id", "",
		"specific core ID to cancel")
	cmd.Flags().BoolVar(&opts.Force, "force", false,
		"force cancellation without graceful shutdown")

	return cmd
}
